package com.phs.main.common.documents;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.phs.main.web.po.Announcement;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class PDFUtil {

	public static void getPDF(String filename, List<?> list, HttpServletResponse response) throws IOException {
		//告诉浏览器用什么软件可以打开此文件
		response.setContentType("application/pdf");
		//下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".pdf");
		response.setCharacterEncoding("UTF-8");

		Document document = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(document, response.getOutputStream());
			document.open();
			document.addLanguage("中文");
			document.addTitle("公告");
			list.forEach(o -> {
				try {
					document.add(getTable((Announcement) o));
				} catch (DocumentException e) {
					e.printStackTrace();
				}
			});
		} catch (FileNotFoundException | DocumentException e) {
			e.printStackTrace();
		} finally {
			document.close();
		}
	}

	private static PdfPTable getTable(Announcement announcement) {
		float tableSize = 6 * 15;
		float fontSize = 10;

		FontSelector fontSelector = new FontSelector();
		fontSelector.addFont(FontFactory.getFont(FontFactory.TIMES_ROMAN, fontSize));
		fontSelector.addFont(FontFactory.getFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, fontSize * 1.5f));
		fontSelector.addFont(FontFactory.getFont("UniGB-UTF8-H", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, fontSize));

		//	表格
		PdfPTable pTable = new PdfPTable(1);
		PdfPCell cell;

		cell = new PdfPCell(fontSelector.process("(" + announcement.getAnnouncementId() + ")\t" + announcement.getAnnouncementName()));
		cell.setFixedHeight(tableSize);
		//设置水平居中
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		//设置垂直居中
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		pTable.addCell(cell);

		cell = new PdfPCell(fontSelector.process(String.valueOf(announcement.getAnnouncementDate())));
		cell.setFixedHeight(tableSize / 2);
		//设置水平居中
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		//设置垂直居中
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		pTable.addCell(cell);

		cell = new PdfPCell(fontSelector.process(announcement.getAnnouncementContent() + "\n\n(" + announcement.getComment() + ")"));
		cell.setFixedHeight(tableSize * 5 * 1.3f);
		//设置水平居中
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		//设置垂直居中
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		pTable.addCell(cell);

		return pTable;
	}
}
